package com.familyaccount.util;

import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Slf4j
public class EmailUtil {
    private static Properties emailProps;
    private static String username;
    private static String password;

    static {
        try {
            emailProps = new Properties();
            InputStream inputStream = EmailUtil.class.getClassLoader().getResourceAsStream("email.properties");
            if (inputStream != null) {
                emailProps.load(inputStream);
                username = emailProps.getProperty("mail.username");
                password = emailProps.getProperty("mail.password");
            } else {
                log.error("Could not find email.properties");
                throw new RuntimeException("Could not find email.properties");
            }
        } catch (IOException e) {
            log.error("Error loading email properties", e);
            throw new RuntimeException("Could not load email properties", e);
        }
    }

    public static boolean sendEmail(String to, String subject, String content) {
        try {
            Session session = Session.getInstance(emailProps, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(content);

            Transport.send(message);
            log.info("Email sent successfully to: {}", to);
            return true;
        } catch (MessagingException e) {
            log.error("Failed to send email to: " + to, e);
            return false;
        }
    }
} 